package com.moss.system.service.impl;


import com.moss.common.constant.Constants;
import com.moss.common.domain.TreeEntity;
import com.moss.common.exception.ServiceException;
import com.moss.common.util.TokenUtil;
import com.moss.common.entity.SysMenuEntity;
import com.moss.system.mapper.MenuMapper;
import com.moss.system.service.MenuService;
import com.moss.common.vo.menu.MetaVO;
import com.moss.common.vo.menu.RouterVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    MenuMapper menuMapper;

    @Override
    public Set<String> selectMenuPermsByUserId(String userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysMenuEntity> selectMenuListByUserId(String userId) {
        List<SysMenuEntity> menus = null;
        if (TokenUtil.isAdmin(userId,Constants.ADMIN_KEY))
        {
            menus = menuMapper.selectMenuTreeAll();
        }
        else
        {
            menus = menuMapper.selectMenuListByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenuEntity> getChildPerms(List<SysMenuEntity> list, int parentId)
    {
        List<SysMenuEntity> returnList = new ArrayList<SysMenuEntity>();
        for (Iterator<SysMenuEntity> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenuEntity t = iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenuEntity> list, SysMenuEntity t)
    {
        // 得到子节点列表
        List<SysMenuEntity> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenuEntity tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenuEntity> getChildList(List<SysMenuEntity> list, SysMenuEntity t)
    {
        List<SysMenuEntity> tlist = new ArrayList<>();
        Iterator<SysMenuEntity> it = list.iterator();
        while (it.hasNext())
        {
            SysMenuEntity n = it.next();
            if (t.getMenuId().equals(n.getParentId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenuEntity> list, SysMenuEntity t)
    {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public List<RouterVO> buildMenus(List<SysMenuEntity> menus) {
        List<RouterVO> routers = new LinkedList<RouterVO>();
        for (SysMenuEntity menu : menus)
        {
            RouterVO router = new RouterVO();
            router.setHidden(0 == menu.getVisible());
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), 0 == menu.getIsCache(), menu.getPath()));
            List<SysMenuEntity> cMenus = menu.getChildren();
            if (cMenus != null && !cMenus.isEmpty() && Constants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                router.setMeta(null);
                List<RouterVO> childrenList = new ArrayList<RouterVO>();
                RouterVO children = new RouterVO();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(getRouteName(menu.getRouteName(), menu.getPath()));
                children.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), 0 == menu.getIsCache(), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if (menu.getParentId().intValue() == 0 && isInnerLink(menu))
            {
                router.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVO> childrenList = new ArrayList<RouterVO>();
                RouterVO children = new RouterVO();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(Constants.INNER_LINK);
                children.setName(getRouteName(menu.getRouteName(), routerPath));
                children.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenuEntity menu)
    {
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            return StringUtils.EMPTY;
        }
        return getRouteName(menu.getRouteName(), menu.getPath());
    }
    /**
     * 获取路由名称，如没有配置路由名称则取路由地址
     *
     * @param name 路由名称
     * @param path 路由地址
     * @return 路由名称（驼峰格式）
     */
    public String getRouteName(String name, String path)
    {
        String routerName = StringUtils.isNotEmpty(name) ? name : path;
        return StringUtils.capitalize(routerName);
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuEntity menu)
    {
        return 0 == menu.getParentId() && Constants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(Constants.NO_FRAME);
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuEntity menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && Constants.TYPE_DIR.equals(menu.getMenuType())
                && Constants.NO_FRAME.equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuEntity menu)
    {
        String component = Constants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            component = Constants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = Constants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenuEntity menu)
    {
        return 0 != menu.getParentId() && Constants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenuEntity menu)
    {
        return menu.getIsFrame().equals(Constants.NO_FRAME) && StringUtils.startsWithAny(menu.getPath(),Constants.HTTP,Constants.HTTPS);
    }

    @Override
    public List<SysMenuEntity> selectMenuList(SysMenuEntity menu, String userId) {
        List<SysMenuEntity> menuList = null;
        // 管理员显示所有菜单信息
        if (TokenUtil.isAdmin(userId,Constants.ADMIN_KEY))
        {
            menuList = menuMapper.selectMenuList(menu);
        }
        else
        {
            menuList = menuMapper.selectMenuListByUserId(menu,userId);
        }
        return menuList;
    }


    //    @Override
//    public List<TreeNode> buildMenuTree(int level, String parentId, String userId) {
//        return this.buildMenuTreeExcludeChild(level, parentId,userId, "");
//    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path)
    {
        return StringUtils.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":" },
                new String[] { "", "", "", "/", "/" });
    }


    @Override
    public List<TreeEntity> buildMenu2Tree(List<SysMenuEntity> menus) {
        List<SysMenuEntity> menuTree = buildMenuTree(menus);
        return menuTree.stream().map(TreeEntity::new).collect(Collectors.toList());
    }

    private List<SysMenuEntity> buildMenuTree(List<SysMenuEntity> menus) {
        return menus.stream().filter(m -> m.getParentId() == 0).peek(
                (m) -> m.setChildren(getChildrenList(m, menus))
        ).collect(Collectors.toList());
    }

    private List<SysMenuEntity> getChildrenList(SysMenuEntity root, List<SysMenuEntity> all) {
        return all.stream().filter(m -> Objects.equals(m.getParentId(), root.getMenuId())).peek(
                (m) -> m.setChildren(getChildrenList(m, all))
        ).collect(Collectors.toList());
    }


    @Override
    public List<Long> selectMenuIdListByRoleId(Long roleId) {
        return menuMapper.selectMenuIdListByRoleId(roleId);
    }

    @Override
    public SysMenuEntity selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    @Override
    public void saveMenu(SysMenuEntity menu) {
        checkMenu(menu,true);
        menuMapper.insert(menu);
    }

    /**
     * 新增修改时校验
     * @param menu 校验菜单数据
     * @param save 是否为保存，true保存，false修改
     */
    private void checkMenu(SysMenuEntity menu, boolean save) {
        if (menu.getIsFrame() == 1 && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTPS,Constants.HTTP)) {
            throw new ServiceException("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        SysMenuEntity sysMenu = menuMapper.selectMenuByName(menu.getMenuName(),menu.getParentId());
        if (save && sysMenu != null){//新增
            throw new ServiceException("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        if (!save && sysMenu != null && !sysMenu.getMenuId().equals(menu.getMenuId())){//修改
            throw new ServiceException("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
    }


    @Override
    public void updateMenu(SysMenuEntity menu) {
        checkMenu(menu,false);
        menuMapper.updateById(menu);
    }

    @Override
    public void deleteMenu(Long menuId) {
        if (menuMapper.hasChildren(menuId)){
            throw new ServiceException("存在子菜单,不允许删除");
        }
        if (menuMapper.checkMenuExistRole(menuId)){
            throw new ServiceException("菜单已分配,不允许删除");
        }
        SysMenuEntity menu = new SysMenuEntity();
        menu.setMenuId(menuId);
        menu.setDelFlag(0);
        menuMapper.updateById(menu);
    }
}
